package com.example.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.pojo.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class TokenUtil {

    private static UserService staticUserService;

    @Autowired
    private UserService userService;

    //通过构造器为staticUserService注入对象
    public TokenUtil(UserService userService) {
        staticUserService = userService;
    }

    /**
     * 生成token
     *
     * @param userId
     * @param password
     * @return
     */
    public static String createToken(String userId, String password) {
        //将userId作为载荷储存到token中
        return JWT.create().withAudience(userId)
                //设置token过期时间2小时
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2))
                //将用户密码进行HMAC256加密后作为密钥
                .sign(Algorithm.HMAC256(password));
    }

    /**
     * 获取当前登录用户的信息
     *
     * @return
     */
    public static User getCurrentUser() {
        try {
            //获取当前线程中的HttpServletRequest对象
            //RequestContextHolder.getRequestAttributes()用于获取当前线程中的请求属性
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StrUtil.isNotBlank(token)) {
                String userId = JWT.decode(token).getAudience().get(0);
                return staticUserService.getById(Integer.valueOf(userId));
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }
}
